/**
 * @filename:DocumentInfoController 2025-04-27
 * @project starhub-schema  V1.0
 */
package com.starhub.engine.document.controller;

import cn.hutool.core.bean.BeanUtil;
import com.starhub.engine.document.entity.DocumentInfo;
import com.starhub.engine.document.request.DocumentInfoBsRequest;
import com.starhub.engine.document.result.DocumentDealListResult;
import com.starhub.engine.document.result.DocumentDealResult;
import com.starhub.engine.document.service.DocumentInfoService;
import com.starhub.common.bean.ResultResp;
import com.starhub.common.security.util.SecurityUtils;
import com.starhub.common.sys.user.LoginUser;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
/**   
 * <p>说明： 附件管理API接口层</P>
 * @version: V1.0
 * @author: 孙赛赛-sss
 * @time    2025-04-27
 *
 */
@Api(value="附件管理后台接口", tags = {"附件管理后台接口"},description = "编写者:孙赛赛-sss" )
@RestController
@RequestMapping("/engine/starhub/document")
public class DocumentInfoConfigController {
    @Autowired
    private DocumentInfoService documentService;
    /**
    * 日志
    */
    private static final Logger log = LoggerFactory.getLogger(DocumentInfoConfigController.class);

    /**
    * 附件管理新增
    */
    @ApiOperation(value = "附件管理新增", notes = "附件管理新增")
    @PostMapping("/addDocumentInfo")
    public ResultResp<DocumentDealListResult> addDocumentInfo(@RequestParam("file") MultipartFile file,@RequestBody DocumentInfo document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.addDocumentInfo(new MultipartFile[]{file},user, document));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    /**
    * 附件管理修改
    */
    @ApiOperation(value = "附件管理修改", notes = "附件管理修改")
    @PostMapping("/updateDocumentInfo")
    public ResultResp<DocumentDealResult> updateDocumentInfo(@RequestBody DocumentInfo document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.updateDocumentInfo(user, document));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    /**
    * 附件管理信息获取
    */
    @ApiOperation(value = "附件管理信息获取", notes = "附件管理信息获取")
    @GetMapping("/getDocumentInfoInfo/{id}")
    public ResultResp<DocumentDealResult> getDocumentInfoInfo(@PathVariable Long id){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.getDocumentInfoInfo(user, id));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    /**
    * 附件管理物理删除
    */
    @ApiOperation(value = "附件管理物理删除", notes = "附件管理物理删除")
    @PostMapping("/deleteDocumentInfoRecord")
    public ResultResp<DocumentDealResult> deleteDocumentInfoRecord(@RequestBody DocumentInfoBsRequest documentInfoBsRequest){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.deleteDocumentInfoRecord(user, documentInfoBsRequest.getIds()));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    /**
    * 附件管理列表获取
    */
    @ApiOperation(value = "附件管理列表获取", notes = "附件管理列表获取")
    @GetMapping("/getDocumentInfoList")
    public ResultResp<DocumentDealListResult> getDocumentInfoList(@RequestBody DocumentInfo document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            Map<String , Object> params = BeanUtil.beanToMap(document);
            return ResultResp.success(documentService.getDocumentInfoList(user, params));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "目录下附件分页列表获取", notes = "目录下附件分页列表获取")
    @PostMapping("/getDocumentListByDir")
    public ResultResp<DocumentDealListResult> getDocumentListByDir(@RequestBody DocumentInfoBsRequest documentInfoBsRequest){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.getDocumentListByDir(documentInfoBsRequest));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    @SneakyThrows
    @GetMapping(value = "/download/{fileId}")
    @ApiOperation(value = "附件下载", notes = "附件下载")
    public void download(@PathVariable Long fileId, HttpServletResponse response) {
        LoginUser user = SecurityUtils.getCurrentUser();
        if(user==null){
            user = new LoginUser("1");
        }
        Map<String,Object> result = documentService.downloadFile(fileId, user);
        if((Boolean)result.get("status")){
            String filePath = (String)result.get("filePath");
            String fileName = (String)result.get("fileName");
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            fileName = StringUtils.replace(fileName, "/", "");
            fileName = StringUtils.replace(fileName, "%2F", "");
            fileName = StringUtils.replace(fileName, "+", "%20");
            int index = filePath.lastIndexOf(".");
            fileName = fileName +  filePath.substring(index);
            Path path = Paths.get(filePath).toAbsolutePath().normalize();
            // 检查文件是否存在
            File file = path.toFile();
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
                return;
            }
            // 获取文件 MIME 类型
            String contentType = Files.probeContentType(path);
            if (contentType == null) {
                contentType = "application/octet-stream";  // 默认类型
            }

            // 设置响应头
            response.setContentType(contentType);
            response.setContentLengthLong(file.length());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 读取文件并写入响应流
            try (FileInputStream inputStream = new FileInputStream(file);
                 ServletOutputStream outputStream = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;

                // 将文件内容写入响应流
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush(); // 刷新输出流，确保所有数据都写出
            } catch (IOException e) {
                log.error(ExceptionUtils.getStackTrace(e));
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error reading the file.");
            }
        }
    }

    @ApiOperation(value = "根据附件ID获取附件内容", notes = "根据附件ID获取附件内容")
    @PostMapping("/getContentByFileId")
    public ResultResp<DocumentDealResult> getContentByFileId(@RequestBody DocumentInfo document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.getContentByFileId(user, document.getId()));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "根据附件ID获取附件HTML", notes = "根据附件ID获取附件HTML")
    @PostMapping("/getHtmlByFileId")
    public ResultResp<DocumentDealResult> getHtmlByFileId(@RequestBody DocumentInfo document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.getHtmlByFileId(user, document.getId()));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

    /**
     * 需要传递html、fileName、directoryId
     * @param document
     * @return
     */
    @ApiOperation(value = "根据Html生成文档", notes = "根据Html生成文档")
    @PostMapping("/converHtml2Word")
    public ResultResp<DocumentDealResult> converHtml2Word(@RequestBody DocumentInfoBsRequest document){
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            return ResultResp.success(documentService.convertHtml2Word(user,document));
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return ResultResp.fail(e.getMessage(), e);
        }
    }

}